package com.koo.modules.cx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koo.common.utils.MyStrUtil;
import com.koo.common.utils.PageUtils;
import com.koo.common.utils.Query;
import com.koo.modules.cx.dao.CxOrderOutDao;
import com.koo.modules.cx.entity.CxOrderOutEntity;
import com.koo.modules.cx.service.CxOrderOutService;
import com.koo.modules.quartz.constant.B2BConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CxOrderOutServiceImpl extends ServiceImpl<CxOrderOutDao, CxOrderOutEntity> implements CxOrderOutService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Object key = params.get("key");
        LambdaQueryWrapper<CxOrderOutEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(MyStrUtil.isNotEmpty(key), CxOrderOutEntity::getOrderOutId, key)
                .or().eq(MyStrUtil.isNotEmpty(key), CxOrderOutEntity::getOutType, key);

        IPage<CxOrderOutEntity> page = this.page(
                new Query<CxOrderOutEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public String selectMaxOrderId() {
        return baseMapper.selectMaxOrderId();
    }

    @Override
    public void insertByList(List<CxOrderOutEntity> orderOuts, String maxOrderId) {
        Integer maxInsertSize = B2BConstant.MAX_INSERT_SIZE.getNumber();
        Integer listSize = orderOuts.size();
        if (listSize > maxInsertSize) {
            for (int i = 0; i < listSize; i += maxInsertSize) {
                List<CxOrderOutEntity> subList = null;
                if (i + maxInsertSize > listSize) {
                    subList = orderOuts.subList(i, listSize);
                } else {
                    subList = orderOuts.subList(i, i + maxInsertSize);
                }
                this.saveBatch(subList);
            }
        } else {
            this.saveBatch(orderOuts);
        }
    }

}